package com.exceeddata.vcloud.common.config;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 描述: 线程池配置 
 * 创建人: 赵兴炎
 * 日期: 2022年9月6日
 */
@Configuration
public class ThreadPoolConfig implements AsyncConfigurer {
	
	private static final Logger log = LoggerFactory.getLogger(ThreadPoolConfig.class);

	private int corePoolSize = 5;// 线程池维护线程的最少数量
	private int maxPoolSize = 30;// 线程池维护线程的最大数量
	private int queueCapacity = 10; // 缓存队列
	private int keepAlive = 60;// 允许的空闲时间

	@Override
	public Executor getAsyncExecutor() {
		return getThreadPoolTaskExecutor();
	}

	/**
	 * 描述: 处理线程的异常
	 * 创建人: 赵兴炎
	 * 日期: 2022年9月6日
	 */
	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new AsyncUncaughtExceptionHandler() {
			@Override
			public void handleUncaughtException(Throwable throwable, Method method, Object... object) {
				log.error("线程异常", throwable.getMessage());
				log.error(throwable.getLocalizedMessage(), throwable);
				log.error(method.getClass().getName());
			}
		};
	}

	/**
	 * 描述: 配置线程池，拒绝策略使用默认的抛出异常
	 * 创建人: 赵兴炎
	 * 日期: 2022年9月6日
	 */
	public ThreadPoolTaskExecutor getThreadPoolTaskExecutor() {
		ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
		threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
		threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
		threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
		threadPoolTaskExecutor.setThreadNamePrefix("mqExecutor-");
		threadPoolTaskExecutor.setKeepAliveSeconds(keepAlive);
		threadPoolTaskExecutor.initialize();
		return threadPoolTaskExecutor;
	}	
}
